package itheima.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import itheima.common.R;
import itheima.dto.DishDto;
import itheima.entity.Category;
import itheima.entity.Dish;
import itheima.entity.DishFlavor;
import itheima.service.CategorySerevice;
import itheima.service.DishFlavorService;
import itheima.service.DishService;
import jdk.net.SocketFlow;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author shkstart
 * @create 2022-09-17-15:41
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategorySerevice categorySerevice;

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功");
    }

    @GetMapping("/page")
    public R<Page> page (int page,int pageSize,String name){

        //构造分页构造器对象
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        //
        Page<DishDto> dtoPage = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        //添加过滤条件
        lambdaQueryWrapper.like(name != null,Dish::getName,name);

        //添加排序条件
        lambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);

        dishService.page(pageInfo,lambdaQueryWrapper);
        //对象拷贝：参数一拷贝给参数二，参数三是不被拷贝的属性
        BeanUtils.copyProperties(pageInfo,dtoPage,"records");

        //获取不被拷贝的属性
        List<Dish> records = pageInfo.getRecords();
        //使用stream流遍历赋值给item
        List<DishDto> list = records.stream().map((item)->{

            DishDto dishDto = new DishDto();
            //对象拷贝：设置了菜品名称但是其他值时空的
            BeanUtils.copyProperties(item,dishDto);
           Long categor = item.getCategoryId();//分类id
            //根据id来查询分类对象
            Category category = categorySerevice.getById(categor);
            if (category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //分类的名称
            return dishDto;
        }).collect(Collectors.toList());

                dtoPage.setRecords(list);

        return R.success(dtoPage);
    }

    @GetMapping("/{id}")
    ///dish/1397860792492666881
    public R<DishDto> get(@PathVariable Long id){


        DishDto byIdWithFlavor = dishService.getByIdWithFlavor(id);

        return R.success(byIdWithFlavor);
    }

    @DeleteMapping
    //dish?ids=1573128059094528001
    public R<String> delete(@RequestParam List<Long> ids){

//        dishService.removeWithFlavor(id);

        dishService.removeWithFlavor(ids);
        return R.success("删除成功");
    }
    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        return R.success("修改菜品成功");
    }

    @PostMapping("/status/{status}")
    public R<String> Status(@PathVariable Integer status,Long[] ids){
        //将数组转换成集合
        List<Long> list = Arrays.asList(ids);

        //构造器条件构造器
        LambdaUpdateWrapper<Dish> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(Dish::getStatus,status).in(Dish::getId,list);
        dishService.update(lambdaUpdateWrapper);
        return R.success("信息修改成功");
    }

    /**
     * 根据条件查询对应的菜品数据
     * @param dish
     * @return
     */
//    @GetMapping("/list")
//    public R<List<Dish>> list(Dish dish){
//
//        //构造查询条件
//        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        //查询菜品分类名称
//        lambdaQueryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
//        //添加条件，查询状态为1的菜品：（起售：1.，停售：0）
//        lambdaQueryWrapper.eq(Dish::getStatus,1);
//        //添加排序条件
//        lambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//
//        //因为一个菜品类有多个菜，所以转换成集合
//        List<Dish> list = dishService.list(lambdaQueryWrapper);
//
//        return R.success(list);
//
//    }

    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){

        //构造查询条件
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //查询菜品分类名称
        lambdaQueryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，查询状态为1的菜品：（起售：1.，停售：0）
        lambdaQueryWrapper.eq(Dish::getStatus,1);
        //添加排序条件
        lambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        //因为一个菜品类有多个菜，所以转换成集合
        List<Dish> list = dishService.list(lambdaQueryWrapper);

        List<DishDto> dtoList= list.stream().map((item)->{

            //创建dishDto用来封装菜品的基本信息和口味信息
            DishDto dishDto = new DishDto();

            //把菜品的进本信息拷贝给dishDto
            BeanUtils.copyProperties(item,dishDto);

            Long categoryId=item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categorySerevice.getById(categoryId);

            if (category != null){
                String name = category.getName();
                dishDto.setCategoryName(name);

            }
            //当前菜品id
            Long dishId = item.getId();
            //查询口味表中的数据
            LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
            lqw.eq(DishFlavor::getDishId,dishId);
            //SQL:select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavors = dishFlavorService.list(lqw);

            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());
        return R.success(dtoList);

    }
}
